{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "code",
      "source": [
        "!pip install langgraph langchain-google-genai langchain-community langchain-core python-dotenv\n",
        "\n",
        "import os\n",
        "from typing import Annotated, List, Tuple, Union\n",
        "from typing_extensions import TypedDict\n",
        "import operator\n",
        "from langchain_core.messages import BaseMessage, HumanMessage, AIMessage, SystemMessage\n",
        "from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\n",
        "from langchain_google_genai import ChatGoogleGenerativeAI\n",
        "from langgraph.graph import StateGraph, END\n",
        "from langgraph.prebuilt import ToolNode\n",
        "from langgraph.checkpoint.memory import MemorySaver\n",
        "import functools\n",
        "\n",
        "import getpass\n",
        "GOOGLE_API_KEY = getpass.getpass(\"Enter your Google API Key: \")\n",
        "os.environ[\"GOOGLE_API_KEY\"] = GOOGLE_API_KEY"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "1BqEEtkuAu2-",
        "outputId": "b41c3a20-c22a-4db4-cc98-c832fdfa4342"
      },
      "execution_count": 7,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m43.5/43.5 kB\u001b[0m \u001b[31m2.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m881.0/881.0 kB\u001b[0m \u001b[31m29.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m33.2/33.2 MB\u001b[0m \u001b[31m19.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m4.1/4.1 MB\u001b[0m \u001b[31m41.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m305.5/305.5 kB\u001b[0m \u001b[31m12.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m3.3/3.3 MB\u001b[0m \u001b[31m37.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m45.2/45.2 kB\u001b[0m \u001b[31m1.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m236.0/236.0 kB\u001b[0m \u001b[31m8.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m31.3/31.3 MB\u001b[0m \u001b[31m24.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m363.4/363.4 MB\u001b[0m \u001b[31m4.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m13.8/13.8 MB\u001b[0m \u001b[31m67.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m24.6/24.6 MB\u001b[0m \u001b[31m55.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m883.7/883.7 kB\u001b[0m \u001b[31m35.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m664.8/664.8 MB\u001b[0m \u001b[31m1.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m211.5/211.5 MB\u001b[0m \u001b[31m6.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m56.3/56.3 MB\u001b[0m \u001b[31m11.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m127.9/127.9 MB\u001b[0m \u001b[31m8.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m207.5/207.5 MB\u001b[0m \u001b[31m2.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m21.1/21.1 MB\u001b[0m \u001b[31m79.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25h"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "class AgentState(TypedDict):\n",
        "    \"\"\"State shared between all agents in the graph\"\"\"\n",
        "    messages: Annotated[list, operator.add]\n",
        "    next: str\n",
        "    current_agent: str\n",
        "    research_topic: str\n",
        "    findings: dict\n",
        "    final_report: str\n",
        "\n",
        "class AgentResponse(TypedDict):\n",
        "    \"\"\"Standard response format for all agents\"\"\"\n",
        "    content: str\n",
        "    next_agent: str\n",
        "    findings: dict\n",
        "\n",
        "def create_llm(temperature: float = 0.1, model: str = \"gemini-1.5-flash\") -> ChatGoogleGenerativeAI:\n",
        "    \"\"\"Create a configured Gemini LLM instance\"\"\"\n",
        "    return ChatGoogleGenerativeAI(\n",
        "        model=model,\n",
        "        temperature=temperature,\n",
        "        google_api_key=os.environ[\"GOOGLE_API_KEY\"]\n",
        "    )"
      ],
      "metadata": {
        "id": "0ZpRVZsZGQDR"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "def create_research_agent(llm: ChatGoogleGenerativeAI) -> callable:\n",
        "    \"\"\"Creates a research specialist agent for initial data gathering\"\"\"\n",
        "\n",
        "    research_prompt = ChatPromptTemplate.from_messages([\n",
        "        (\"system\", \"\"\"You are a Research Specialist AI. Your role is to:\n",
        "        1. Analyze the research topic thoroughly\n",
        "        2. Identify key areas that need investigation\n",
        "        3. Provide initial research findings and insights\n",
        "        4. Suggest specific angles for deeper analysis\n",
        "\n",
        "        Focus on providing comprehensive, accurate information and clear research directions.\n",
        "        Always structure your response with clear sections and bullet points.\n",
        "        \"\"\"),\n",
        "        MessagesPlaceholder(variable_name=\"messages\"),\n",
        "        (\"human\", \"Research Topic: {research_topic}\")\n",
        "    ])\n",
        "\n",
        "    research_chain = research_prompt | llm\n",
        "\n",
        "    def research_agent(state: AgentState) -> AgentState:\n",
        "        \"\"\"Execute research analysis\"\"\"\n",
        "        try:\n",
        "            response = research_chain.invoke({\n",
        "                \"messages\": state[\"messages\"],\n",
        "                \"research_topic\": state[\"research_topic\"]\n",
        "            })\n",
        "\n",
        "            findings = {\n",
        "                \"research_overview\": response.content,\n",
        "                \"key_areas\": [\"area1\", \"area2\", \"area3\"],\n",
        "                \"initial_insights\": response.content[:500] + \"...\"\n",
        "            }\n",
        "\n",
        "            return {\n",
        "                \"messages\": state[\"messages\"] + [AIMessage(content=response.content)],\n",
        "                \"next\": \"analyst\",\n",
        "                \"current_agent\": \"researcher\",\n",
        "                \"research_topic\": state[\"research_topic\"],\n",
        "                \"findings\": {**state.get(\"findings\", {}), \"research\": findings},\n",
        "                \"final_report\": state.get(\"final_report\", \"\")\n",
        "            }\n",
        "\n",
        "        except Exception as e:\n",
        "            error_msg = f\"Research agent error: {str(e)}\"\n",
        "            return {\n",
        "                \"messages\": state[\"messages\"] + [AIMessage(content=error_msg)],\n",
        "                \"next\": \"analyst\",\n",
        "                \"current_agent\": \"researcher\",\n",
        "                \"research_topic\": state[\"research_topic\"],\n",
        "                \"findings\": state.get(\"findings\", {}),\n",
        "                \"final_report\": state.get(\"final_report\", \"\")\n",
        "            }\n",
        "\n",
        "    return research_agent"
      ],
      "metadata": {
        "id": "nPqQ9-OfGS5I"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "def create_analyst_agent(llm: ChatGoogleGenerativeAI) -> callable:\n",
        "    \"\"\"Creates a data analyst agent for deep analysis\"\"\"\n",
        "\n",
        "    analyst_prompt = ChatPromptTemplate.from_messages([\n",
        "        (\"system\", \"\"\"You are a Data Analyst AI. Your role is to:\n",
        "        1. Analyze data and information provided by the research team\n",
        "        2. Identify patterns, trends, and correlations\n",
        "        3. Provide statistical insights and data-driven conclusions\n",
        "        4. Suggest actionable recommendations based on analysis\n",
        "\n",
        "        Focus on quantitative analysis, data interpretation, and evidence-based insights.\n",
        "        Use clear metrics and concrete examples in your analysis.\n",
        "        \"\"\"),\n",
        "        MessagesPlaceholder(variable_name=\"messages\"),\n",
        "        (\"human\", \"Analyze the research findings for: {research_topic}\")\n",
        "    ])\n",
        "\n",
        "    analyst_chain = analyst_prompt | llm\n",
        "\n",
        "    def analyst_agent(state: AgentState) -> AgentState:\n",
        "        \"\"\"Execute data analysis\"\"\"\n",
        "        try:\n",
        "            response = analyst_chain.invoke({\n",
        "                \"messages\": state[\"messages\"],\n",
        "                \"research_topic\": state[\"research_topic\"]\n",
        "            })\n",
        "\n",
        "            analysis_findings = {\n",
        "                \"analysis_summary\": response.content,\n",
        "                \"key_metrics\": [\"metric1\", \"metric2\", \"metric3\"],\n",
        "                \"recommendations\": response.content.split(\"recommendations:\")[-1] if \"recommendations:\" in response.content.lower() else \"No specific recommendations found\"\n",
        "            }\n",
        "\n",
        "            return {\n",
        "                \"messages\": state[\"messages\"] + [AIMessage(content=response.content)],\n",
        "                \"next\": \"writer\",\n",
        "                \"current_agent\": \"analyst\",\n",
        "                \"research_topic\": state[\"research_topic\"],\n",
        "                \"findings\": {**state.get(\"findings\", {}), \"analysis\": analysis_findings},\n",
        "                \"final_report\": state.get(\"final_report\", \"\")\n",
        "            }\n",
        "\n",
        "        except Exception as e:\n",
        "            error_msg = f\"Analyst agent error: {str(e)}\"\n",
        "            return {\n",
        "                \"messages\": state[\"messages\"] + [AIMessage(content=error_msg)],\n",
        "                \"next\": \"writer\",\n",
        "                \"current_agent\": \"analyst\",\n",
        "                \"research_topic\": state[\"research_topic\"],\n",
        "                \"findings\": state.get(\"findings\", {}),\n",
        "                \"final_report\": state.get(\"final_report\", \"\")\n",
        "            }\n",
        "\n",
        "    return analyst_agent"
      ],
      "metadata": {
        "id": "a2YbN48sGVR1"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "def create_writer_agent(llm: ChatGoogleGenerativeAI) -> callable:\n",
        "    \"\"\"Creates a report writer agent for final documentation\"\"\"\n",
        "\n",
        "    writer_prompt = ChatPromptTemplate.from_messages([\n",
        "        (\"system\", \"\"\"You are a Report Writer AI. Your role is to:\n",
        "        1. Synthesize all research and analysis into a comprehensive report\n",
        "        2. Create clear, professional documentation\n",
        "        3. Ensure proper structure with executive summary, findings, and conclusions\n",
        "        4. Make complex information accessible to various audiences\n",
        "\n",
        "        Focus on clarity, completeness, and professional presentation.\n",
        "        Include specific examples and actionable insights.\n",
        "        \"\"\"),\n",
        "        MessagesPlaceholder(variable_name=\"messages\"),\n",
        "        (\"human\", \"Create a comprehensive report for: {research_topic}\")\n",
        "    ])\n",
        "\n",
        "    writer_chain = writer_prompt | llm\n",
        "\n",
        "    def writer_agent(state: AgentState) -> AgentState:\n",
        "        \"\"\"Execute report writing\"\"\"\n",
        "        try:\n",
        "            response = writer_chain.invoke({\n",
        "                \"messages\": state[\"messages\"],\n",
        "                \"research_topic\": state[\"research_topic\"]\n",
        "            })\n",
        "\n",
        "            return {\n",
        "                \"messages\": state[\"messages\"] + [AIMessage(content=response.content)],\n",
        "                \"next\": \"supervisor\",\n",
        "                \"current_agent\": \"writer\",\n",
        "                \"research_topic\": state[\"research_topic\"],\n",
        "                \"findings\": state.get(\"findings\", {}),\n",
        "                \"final_report\": response.content\n",
        "            }\n",
        "\n",
        "        except Exception as e:\n",
        "            error_msg = f\"Writer agent error: {str(e)}\"\n",
        "            return {\n",
        "                \"messages\": state[\"messages\"] + [AIMessage(content=error_msg)],\n",
        "                \"next\": \"supervisor\",\n",
        "                \"current_agent\": \"writer\",\n",
        "                \"research_topic\": state[\"research_topic\"],\n",
        "                \"findings\": state.get(\"findings\", {}),\n",
        "                \"final_report\": f\"Error generating report: {str(e)}\"\n",
        "            }\n",
        "\n",
        "    return writer_agent"
      ],
      "metadata": {
        "id": "t2Uq4mdaGV-u"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "def create_supervisor_agent(llm: ChatGoogleGenerativeAI, members: List[str]) -> callable:\n",
        "    \"\"\"Creates a supervisor agent to coordinate the team\"\"\"\n",
        "\n",
        "    options = [\"FINISH\"] + members\n",
        "\n",
        "    supervisor_prompt = ChatPromptTemplate.from_messages([\n",
        "        (\"system\", f\"\"\"You are a Supervisor AI managing a research team. Your team members are:\n",
        "        {', '.join(members)}\n",
        "\n",
        "        Your responsibilities:\n",
        "        1. Coordinate the workflow between team members\n",
        "        2. Ensure each agent completes their specialized tasks\n",
        "        3. Determine when the research is complete\n",
        "        4. Maintain quality standards throughout the process\n",
        "\n",
        "        Given the conversation, determine the next step:\n",
        "        - If research is needed: route to \"researcher\"\n",
        "        - If analysis is needed: route to \"analyst\"\n",
        "        - If report writing is needed: route to \"writer\"\n",
        "        - If work is complete: route to \"FINISH\"\n",
        "\n",
        "        Available options: {options}\n",
        "\n",
        "        Respond with just the name of the next agent or \"FINISH\".\n",
        "        \"\"\"),\n",
        "        MessagesPlaceholder(variable_name=\"messages\"),\n",
        "        (\"human\", \"Current status: {current_agent} just completed their task for topic: {research_topic}\")\n",
        "    ])\n",
        "\n",
        "    supervisor_chain = supervisor_prompt | llm\n",
        "\n",
        "    def supervisor_agent(state: AgentState) -> AgentState:\n",
        "        \"\"\"Execute supervisor coordination\"\"\"\n",
        "        try:\n",
        "            response = supervisor_chain.invoke({\n",
        "                \"messages\": state[\"messages\"],\n",
        "                \"current_agent\": state.get(\"current_agent\", \"none\"),\n",
        "                \"research_topic\": state[\"research_topic\"]\n",
        "            })\n",
        "\n",
        "            next_agent = response.content.strip().lower()\n",
        "\n",
        "            if \"finish\" in next_agent or \"complete\" in next_agent:\n",
        "                next_step = \"FINISH\"\n",
        "            elif \"research\" in next_agent:\n",
        "                next_step = \"researcher\"\n",
        "            elif \"analy\" in next_agent:\n",
        "                next_step = \"analyst\"\n",
        "            elif \"writ\" in next_agent:\n",
        "                next_step = \"writer\"\n",
        "            else:\n",
        "                current = state.get(\"current_agent\", \"\")\n",
        "                if current == \"researcher\":\n",
        "                    next_step = \"analyst\"\n",
        "                elif current == \"analyst\":\n",
        "                    next_step = \"writer\"\n",
        "                elif current == \"writer\":\n",
        "                    next_step = \"FINISH\"\n",
        "                else:\n",
        "                    next_step = \"researcher\"\n",
        "\n",
        "            return {\n",
        "                \"messages\": state[\"messages\"] + [AIMessage(content=f\"Supervisor decision: Next agent is {next_step}\")],\n",
        "                \"next\": next_step,\n",
        "                \"current_agent\": \"supervisor\",\n",
        "                \"research_topic\": state[\"research_topic\"],\n",
        "                \"findings\": state.get(\"findings\", {}),\n",
        "                \"final_report\": state.get(\"final_report\", \"\")\n",
        "            }\n",
        "\n",
        "        except Exception as e:\n",
        "            error_msg = f\"Supervisor error: {str(e)}\"\n",
        "            return {\n",
        "                \"messages\": state[\"messages\"] + [AIMessage(content=error_msg)],\n",
        "                \"next\": \"FINISH\",\n",
        "                \"current_agent\": \"supervisor\",\n",
        "                \"research_topic\": state[\"research_topic\"],\n",
        "                \"findings\": state.get(\"findings\", {}),\n",
        "                \"final_report\": state.get(\"final_report\", \"\")\n",
        "            }\n",
        "\n",
        "    return supervisor_agent"
      ],
      "metadata": {
        "id": "0ytoftycGblx"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "def create_research_team_graph() -> StateGraph:\n",
        "    \"\"\"Creates the complete research team workflow graph\"\"\"\n",
        "\n",
        "    llm = create_llm()\n",
        "\n",
        "    members = [\"researcher\", \"analyst\", \"writer\"]\n",
        "    researcher = create_research_agent(llm)\n",
        "    analyst = create_analyst_agent(llm)\n",
        "    writer = create_writer_agent(llm)\n",
        "    supervisor = create_supervisor_agent(llm, members)\n",
        "\n",
        "    workflow = StateGraph(AgentState)\n",
        "\n",
        "    workflow.add_node(\"researcher\", researcher)\n",
        "    workflow.add_node(\"analyst\", analyst)\n",
        "    workflow.add_node(\"writer\", writer)\n",
        "    workflow.add_node(\"supervisor\", supervisor)\n",
        "\n",
        "    workflow.add_edge(\"researcher\", \"supervisor\")\n",
        "    workflow.add_edge(\"analyst\", \"supervisor\")\n",
        "    workflow.add_edge(\"writer\", \"supervisor\")\n",
        "\n",
        "    workflow.add_conditional_edges(\n",
        "        \"supervisor\",\n",
        "        lambda x: x[\"next\"],\n",
        "        {\n",
        "            \"researcher\": \"researcher\",\n",
        "            \"analyst\": \"analyst\",\n",
        "            \"writer\": \"writer\",\n",
        "            \"FINISH\": END\n",
        "        }\n",
        "    )\n",
        "\n",
        "    workflow.set_entry_point(\"supervisor\")\n",
        "\n",
        "    return workflow\n",
        "\n",
        "def compile_research_team():\n",
        "    \"\"\"Compile the research team graph with memory\"\"\"\n",
        "    workflow = create_research_team_graph()\n",
        "\n",
        "    memory = MemorySaver()\n",
        "\n",
        "    app = workflow.compile(checkpointer=memory)\n",
        "\n",
        "    return app\n",
        "\n",
        "def run_research_team(topic: str, thread_id: str = \"research_session_1\"):\n",
        "    \"\"\"Run the complete research team workflow\"\"\"\n",
        "\n",
        "    app = compile_research_team()\n",
        "\n",
        "    initial_state = {\n",
        "        \"messages\": [HumanMessage(content=f\"Research the topic: {topic}\")],\n",
        "        \"research_topic\": topic,\n",
        "        \"next\": \"researcher\",\n",
        "        \"current_agent\": \"start\",\n",
        "        \"findings\": {},\n",
        "        \"final_report\": \"\"\n",
        "    }\n",
        "\n",
        "    config = {\"configurable\": {\"thread_id\": thread_id}}\n",
        "\n",
        "    print(f\"🔍 Starting research on: {topic}\")\n",
        "    print(\"=\" * 50)\n",
        "\n",
        "    try:\n",
        "        final_state = None\n",
        "        for step, state in enumerate(app.stream(initial_state, config=config)):\n",
        "            print(f\"\\n📍 Step {step + 1}: {list(state.keys())[0]}\")\n",
        "\n",
        "            current_state = list(state.values())[0]\n",
        "            if current_state[\"messages\"]:\n",
        "                last_message = current_state[\"messages\"][-1]\n",
        "                if isinstance(last_message, AIMessage):\n",
        "                    print(f\"💬 {last_message.content[:200]}...\")\n",
        "\n",
        "            final_state = current_state\n",
        "\n",
        "            if step > 10:\n",
        "                print(\"⚠️  Maximum steps reached. Stopping execution.\")\n",
        "                break\n",
        "\n",
        "        return final_state\n",
        "\n",
        "    except Exception as e:\n",
        "        print(f\"❌ Error during execution: {str(e)}\")\n",
        "        return None"
      ],
      "metadata": {
        "id": "o-DXR3wmGhlP"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "if __name__ == \"__main__\":\n",
        "    result = run_research_team(\"Artificial Intelligence in Healthcare\")\n",
        "\n",
        "    if result:\n",
        "        print(\"\\n\" + \"=\" * 50)\n",
        "        print(\"📊 FINAL RESULTS\")\n",
        "        print(\"=\" * 50)\n",
        "        print(f\"🏁 Final Agent: {result['current_agent']}\")\n",
        "        print(f\"📋 Findings: {len(result['findings'])} sections\")\n",
        "        print(f\"📄 Report Length: {len(result['final_report'])} characters\")\n",
        "\n",
        "        if result['final_report']:\n",
        "            print(\"\\n📄 FINAL REPORT:\")\n",
        "            print(\"-\" * 30)\n",
        "            print(result['final_report'])\n",
        "\n",
        "def interactive_research_session():\n",
        "    \"\"\"Run an interactive research session\"\"\"\n",
        "\n",
        "    app = compile_research_team()\n",
        "\n",
        "    print(\"🎯 Interactive Research Team Session\")\n",
        "    print(\"Enter 'quit' to exit\\n\")\n",
        "\n",
        "    session_count = 0\n",
        "\n",
        "    while True:\n",
        "        topic = input(\"🔍 Enter research topic: \").strip()\n",
        "\n",
        "        if topic.lower() in ['quit', 'exit', 'q']:\n",
        "            print(\"👋 Goodbye!\")\n",
        "            break\n",
        "\n",
        "        if not topic:\n",
        "            print(\"❌ Please enter a valid topic.\")\n",
        "            continue\n",
        "\n",
        "        session_count += 1\n",
        "        thread_id = f\"interactive_session_{session_count}\"\n",
        "\n",
        "        result = run_research_team(topic, thread_id)\n",
        "\n",
        "        if result and result['final_report']:\n",
        "            print(f\"\\n✅ Research completed for: {topic}\")\n",
        "            print(f\"📄 Report preview: {result['final_report'][:300]}...\")\n",
        "\n",
        "            show_full = input(\"\\n📖 Show full report? (y/n): \").lower()\n",
        "            if show_full.startswith('y'):\n",
        "                print(\"\\n\" + \"=\" * 60)\n",
        "                print(\"📄 COMPLETE RESEARCH REPORT\")\n",
        "                print(\"=\" * 60)\n",
        "                print(result['final_report'])\n",
        "\n",
        "        print(\"\\n\" + \"-\" * 50)\n",
        "\n",
        "\n",
        "def create_custom_agent(role: str, instructions: str, llm: ChatGoogleGenerativeAI) -> callable:\n",
        "    \"\"\"Create a custom agent with specific role and instructions\"\"\"\n",
        "\n",
        "    custom_prompt = ChatPromptTemplate.from_messages([\n",
        "        (\"system\", f\"\"\"You are a {role} AI.\n",
        "\n",
        "        Your specific instructions:\n",
        "        {instructions}\n",
        "\n",
        "        Always provide detailed, professional responses relevant to your role.\n",
        "        \"\"\"),\n",
        "        MessagesPlaceholder(variable_name=\"messages\"),\n",
        "        (\"human\", \"Task: {task}\")\n",
        "    ])\n",
        "\n",
        "    custom_chain = custom_prompt | llm\n",
        "\n",
        "    def custom_agent(state: AgentState) -> AgentState:\n",
        "        \"\"\"Execute custom agent task\"\"\"\n",
        "        try:\n",
        "            response = custom_chain.invoke({\n",
        "                \"messages\": state[\"messages\"],\n",
        "                \"task\": state[\"research_topic\"]\n",
        "            })\n",
        "\n",
        "            return {\n",
        "                \"messages\": state[\"messages\"] + [AIMessage(content=response.content)],\n",
        "                \"next\": \"supervisor\",\n",
        "                \"current_agent\": role.lower().replace(\" \", \"_\"),\n",
        "                \"research_topic\": state[\"research_topic\"],\n",
        "                \"findings\": state.get(\"findings\", {}),\n",
        "                \"final_report\": state.get(\"final_report\", \"\")\n",
        "            }\n",
        "\n",
        "        except Exception as e:\n",
        "            error_msg = f\"{role} agent error: {str(e)}\"\n",
        "            return {\n",
        "                \"messages\": state[\"messages\"] + [AIMessage(content=error_msg)],\n",
        "                \"next\": \"supervisor\",\n",
        "                \"current_agent\": role.lower().replace(\" \", \"_\"),\n",
        "                \"research_topic\": state[\"research_topic\"],\n",
        "                \"findings\": state.get(\"findings\", {}),\n",
        "                \"final_report\": state.get(\"final_report\", \"\")\n",
        "            }\n",
        "\n",
        "    return custom_agent"
      ],
      "metadata": {
        "id": "3Q7HM7JzGlzY"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "def visualize_graph():\n",
        "    \"\"\"Visualize the research team graph structure\"\"\"\n",
        "\n",
        "    try:\n",
        "        app = compile_research_team()\n",
        "\n",
        "        graph_repr = app.get_graph()\n",
        "\n",
        "        print(\"🗺️  Research Team Graph Structure\")\n",
        "        print(\"=\" * 40)\n",
        "        print(f\"Nodes: {list(graph_repr.nodes.keys())}\")\n",
        "        print(f\"Edges: {[(edge.source, edge.target) for edge in graph_repr.edges]}\")\n",
        "\n",
        "        try:\n",
        "            graph_repr.draw_mermaid()\n",
        "        except:\n",
        "            print(\"📊 Visual graph requires mermaid-py package\")\n",
        "            print(\"Install with: !pip install mermaid-py\")\n",
        "\n",
        "    except Exception as e:\n",
        "        print(f\"❌ Error visualizing graph: {str(e)}\")\n",
        "\n",
        "\n",
        "import time\n",
        "from datetime import datetime\n",
        "\n",
        "def monitor_research_performance(topic: str):\n",
        "    \"\"\"Monitor and report performance metrics\"\"\"\n",
        "\n",
        "    start_time = time.time()\n",
        "    print(f\"⏱️  Starting performance monitoring for: {topic}\")\n",
        "\n",
        "    result = run_research_team(topic, f\"perf_test_{int(time.time())}\")\n",
        "\n",
        "    end_time = time.time()\n",
        "    duration = end_time - start_time\n",
        "\n",
        "    metrics = {\n",
        "        \"duration\": duration,\n",
        "        \"total_messages\": len(result[\"messages\"]) if result else 0,\n",
        "        \"findings_sections\": len(result[\"findings\"]) if result else 0,\n",
        "        \"report_length\": len(result[\"final_report\"]) if result and result[\"final_report\"] else 0,\n",
        "        \"success\": result is not None\n",
        "    }\n",
        "\n",
        "    print(\"\\n📊 PERFORMANCE METRICS\")\n",
        "    print(\"=\" * 30)\n",
        "    print(f\"⏱️  Duration: {duration:.2f} seconds\")\n",
        "    print(f\"💬 Total Messages: {metrics['total_messages']}\")\n",
        "    print(f\"📋 Findings Sections: {metrics['findings_sections']}\")\n",
        "    print(f\"📄 Report Length: {metrics['report_length']} chars\")\n",
        "    print(f\"✅ Success: {metrics['success']}\")\n",
        "\n",
        "    return metrics\n",
        "\n",
        "\n",
        "def quick_start_demo():\n",
        "    \"\"\"Complete demo of the research team system\"\"\"\n",
        "\n",
        "    print(\"🚀 LangGraph Research Team - Quick Start Demo\")\n",
        "    print(\"=\" * 50)\n",
        "\n",
        "    topics = [\n",
        "        \"Climate Change Impact on Agriculture\",\n",
        "        \"Quantum Computing Applications\",\n",
        "        \"Digital Privacy in the Modern Age\"\n",
        "    ]\n",
        "\n",
        "    for i, topic in enumerate(topics, 1):\n",
        "        print(f\"\\n🔍 Demo {i}: {topic}\")\n",
        "        print(\"-\" * 40)\n",
        "\n",
        "        try:\n",
        "            result = run_research_team(topic, f\"demo_{i}\")\n",
        "\n",
        "            if result and result['final_report']:\n",
        "                print(f\"✅ Research completed successfully!\")\n",
        "                print(f\"📊 Report preview: {result['final_report'][:150]}...\")\n",
        "            else:\n",
        "                print(\"❌ Research failed\")\n",
        "\n",
        "        except Exception as e:\n",
        "            print(f\"❌ Error in demo {i}: {str(e)}\")\n",
        "\n",
        "        print(\"\\n\" + \"=\"*30)\n",
        "\n",
        "    print(\"🎉 Demo completed!\")\n",
        "\n",
        "quick_start_demo()"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "jw3b39JqEZNk",
        "outputId": "dcc1cc73-6285-48b4-efa2-e8c30d718245"
      },
      "execution_count": 12,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Requirement already satisfied: langgraph in /usr/local/lib/python3.11/dist-packages (0.5.1)\n",
            "Requirement already satisfied: langchain-google-genai in /usr/local/lib/python3.11/dist-packages (2.1.6)\n",
            "Requirement already satisfied: langchain-community in /usr/local/lib/python3.11/dist-packages (0.3.27)\n",
            "Requirement already satisfied: langchain-core in /usr/local/lib/python3.11/dist-packages (0.3.67)\n",
            "Requirement already satisfied: python-dotenv in /usr/local/lib/python3.11/dist-packages (1.1.1)\n",
            "Requirement already satisfied: langgraph-checkpoint<3.0.0,>=2.1.0 in /usr/local/lib/python3.11/dist-packages (from langgraph) (2.1.0)\n",
            "Requirement already satisfied: langgraph-prebuilt<0.6.0,>=0.5.0 in /usr/local/lib/python3.11/dist-packages (from langgraph) (0.5.2)\n",
            "Requirement already satisfied: langgraph-sdk<0.2.0,>=0.1.42 in /usr/local/lib/python3.11/dist-packages (from langgraph) (0.1.72)\n",
            "Requirement already satisfied: pydantic>=2.7.4 in /usr/local/lib/python3.11/dist-packages (from langgraph) (2.11.7)\n",
            "Requirement already satisfied: xxhash>=3.5.0 in /usr/local/lib/python3.11/dist-packages (from langgraph) (3.5.0)\n",
            "Requirement already satisfied: filetype<2.0.0,>=1.2.0 in /usr/local/lib/python3.11/dist-packages (from langchain-google-genai) (1.2.0)\n",
            "Requirement already satisfied: google-ai-generativelanguage<0.7.0,>=0.6.18 in /usr/local/lib/python3.11/dist-packages (from langchain-google-genai) (0.6.18)\n",
            "Requirement already satisfied: langchain<1.0.0,>=0.3.26 in /usr/local/lib/python3.11/dist-packages (from langchain-community) (0.3.26)\n",
            "Requirement already satisfied: SQLAlchemy<3,>=1.4 in /usr/local/lib/python3.11/dist-packages (from langchain-community) (2.0.41)\n",
            "Requirement already satisfied: requests<3,>=2 in /usr/local/lib/python3.11/dist-packages (from langchain-community) (2.32.3)\n",
            "Requirement already satisfied: PyYAML>=5.3 in /usr/local/lib/python3.11/dist-packages (from langchain-community) (6.0.2)\n",
            "Requirement already satisfied: aiohttp<4.0.0,>=3.8.3 in /usr/local/lib/python3.11/dist-packages (from langchain-community) (3.11.15)\n",
            "Requirement already satisfied: tenacity!=8.4.0,<10,>=8.1.0 in /usr/local/lib/python3.11/dist-packages (from langchain-community) (8.5.0)\n",
            "Requirement already satisfied: dataclasses-json<0.7,>=0.5.7 in /usr/local/lib/python3.11/dist-packages (from langchain-community) (0.6.7)\n",
            "Requirement already satisfied: pydantic-settings<3.0.0,>=2.4.0 in /usr/local/lib/python3.11/dist-packages (from langchain-community) (2.10.1)\n",
            "Requirement already satisfied: langsmith>=0.1.125 in /usr/local/lib/python3.11/dist-packages (from langchain-community) (0.4.4)\n",
            "Requirement already satisfied: httpx-sse<1.0.0,>=0.4.0 in /usr/local/lib/python3.11/dist-packages (from langchain-community) (0.4.1)\n",
            "Requirement already satisfied: numpy>=1.26.2 in /usr/local/lib/python3.11/dist-packages (from langchain-community) (2.0.2)\n",
            "Requirement already satisfied: jsonpatch<2.0,>=1.33 in /usr/local/lib/python3.11/dist-packages (from langchain-core) (1.33)\n",
            "Requirement already satisfied: packaging<25,>=23.2 in /usr/local/lib/python3.11/dist-packages (from langchain-core) (24.2)\n",
            "Requirement already satisfied: typing-extensions>=4.7 in /usr/local/lib/python3.11/dist-packages (from langchain-core) (4.14.0)\n",
            "Requirement already satisfied: aiohappyeyeballs>=2.3.0 in /usr/local/lib/python3.11/dist-packages (from aiohttp<4.0.0,>=3.8.3->langchain-community) (2.6.1)\n",
            "Requirement already satisfied: aiosignal>=1.1.2 in /usr/local/lib/python3.11/dist-packages (from aiohttp<4.0.0,>=3.8.3->langchain-community) (1.3.2)\n",
            "Requirement already satisfied: attrs>=17.3.0 in /usr/local/lib/python3.11/dist-packages (from aiohttp<4.0.0,>=3.8.3->langchain-community) (25.3.0)\n",
            "Requirement already satisfied: frozenlist>=1.1.1 in /usr/local/lib/python3.11/dist-packages (from aiohttp<4.0.0,>=3.8.3->langchain-community) (1.7.0)\n",
            "Requirement already satisfied: multidict<7.0,>=4.5 in /usr/local/lib/python3.11/dist-packages (from aiohttp<4.0.0,>=3.8.3->langchain-community) (6.6.3)\n",
            "Requirement already satisfied: propcache>=0.2.0 in /usr/local/lib/python3.11/dist-packages (from aiohttp<4.0.0,>=3.8.3->langchain-community) (0.3.2)\n",
            "Requirement already satisfied: yarl<2.0,>=1.17.0 in /usr/local/lib/python3.11/dist-packages (from aiohttp<4.0.0,>=3.8.3->langchain-community) (1.20.1)\n",
            "Requirement already satisfied: marshmallow<4.0.0,>=3.18.0 in /usr/local/lib/python3.11/dist-packages (from dataclasses-json<0.7,>=0.5.7->langchain-community) (3.26.1)\n",
            "Requirement already satisfied: typing-inspect<1,>=0.4.0 in /usr/local/lib/python3.11/dist-packages (from dataclasses-json<0.7,>=0.5.7->langchain-community) (0.9.0)\n",
            "Requirement already satisfied: google-api-core!=2.0.*,!=2.1.*,!=2.10.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,<3.0.0,>=1.34.1 in /usr/local/lib/python3.11/dist-packages (from google-api-core[grpc]!=2.0.*,!=2.1.*,!=2.10.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,<3.0.0,>=1.34.1->google-ai-generativelanguage<0.7.0,>=0.6.18->langchain-google-genai) (2.25.1)\n",
            "Requirement already satisfied: google-auth!=2.24.0,!=2.25.0,<3.0.0,>=2.14.1 in /usr/local/lib/python3.11/dist-packages (from google-ai-generativelanguage<0.7.0,>=0.6.18->langchain-google-genai) (2.38.0)\n",
            "Requirement already satisfied: proto-plus<2.0.0,>=1.22.3 in /usr/local/lib/python3.11/dist-packages (from google-ai-generativelanguage<0.7.0,>=0.6.18->langchain-google-genai) (1.26.1)\n",
            "Requirement already satisfied: protobuf!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5,<7.0.0,>=3.20.2 in /usr/local/lib/python3.11/dist-packages (from google-ai-generativelanguage<0.7.0,>=0.6.18->langchain-google-genai) (5.29.5)\n",
            "Requirement already satisfied: jsonpointer>=1.9 in /usr/local/lib/python3.11/dist-packages (from jsonpatch<2.0,>=1.33->langchain-core) (3.0.0)\n",
            "Requirement already satisfied: langchain-text-splitters<1.0.0,>=0.3.8 in /usr/local/lib/python3.11/dist-packages (from langchain<1.0.0,>=0.3.26->langchain-community) (0.3.8)\n",
            "Requirement already satisfied: ormsgpack>=1.10.0 in /usr/local/lib/python3.11/dist-packages (from langgraph-checkpoint<3.0.0,>=2.1.0->langgraph) (1.10.0)\n",
            "Requirement already satisfied: httpx>=0.25.2 in /usr/local/lib/python3.11/dist-packages (from langgraph-sdk<0.2.0,>=0.1.42->langgraph) (0.28.1)\n",
            "Requirement already satisfied: orjson>=3.10.1 in /usr/local/lib/python3.11/dist-packages (from langgraph-sdk<0.2.0,>=0.1.42->langgraph) (3.10.18)\n",
            "Requirement already satisfied: requests-toolbelt<2.0.0,>=1.0.0 in /usr/local/lib/python3.11/dist-packages (from langsmith>=0.1.125->langchain-community) (1.0.0)\n",
            "Requirement already satisfied: zstandard<0.24.0,>=0.23.0 in /usr/local/lib/python3.11/dist-packages (from langsmith>=0.1.125->langchain-community) (0.23.0)\n",
            "Requirement already satisfied: annotated-types>=0.6.0 in /usr/local/lib/python3.11/dist-packages (from pydantic>=2.7.4->langgraph) (0.7.0)\n",
            "Requirement already satisfied: pydantic-core==2.33.2 in /usr/local/lib/python3.11/dist-packages (from pydantic>=2.7.4->langgraph) (2.33.2)\n",
            "Requirement already satisfied: typing-inspection>=0.4.0 in /usr/local/lib/python3.11/dist-packages (from pydantic>=2.7.4->langgraph) (0.4.1)\n",
            "Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.11/dist-packages (from requests<3,>=2->langchain-community) (3.4.2)\n",
            "Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.11/dist-packages (from requests<3,>=2->langchain-community) (3.10)\n",
            "Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.11/dist-packages (from requests<3,>=2->langchain-community) (2.4.0)\n",
            "Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.11/dist-packages (from requests<3,>=2->langchain-community) (2025.6.15)\n",
            "Requirement already satisfied: greenlet>=1 in /usr/local/lib/python3.11/dist-packages (from SQLAlchemy<3,>=1.4->langchain-community) (3.2.3)\n",
            "Requirement already satisfied: googleapis-common-protos<2.0.0,>=1.56.2 in /usr/local/lib/python3.11/dist-packages (from google-api-core!=2.0.*,!=2.1.*,!=2.10.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,<3.0.0,>=1.34.1->google-api-core[grpc]!=2.0.*,!=2.1.*,!=2.10.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,<3.0.0,>=1.34.1->google-ai-generativelanguage<0.7.0,>=0.6.18->langchain-google-genai) (1.70.0)\n",
            "Requirement already satisfied: grpcio<2.0.0,>=1.33.2 in /usr/local/lib/python3.11/dist-packages (from google-api-core[grpc]!=2.0.*,!=2.1.*,!=2.10.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,<3.0.0,>=1.34.1->google-ai-generativelanguage<0.7.0,>=0.6.18->langchain-google-genai) (1.73.1)\n",
            "Requirement already satisfied: grpcio-status<2.0.0,>=1.33.2 in /usr/local/lib/python3.11/dist-packages (from google-api-core[grpc]!=2.0.*,!=2.1.*,!=2.10.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,<3.0.0,>=1.34.1->google-ai-generativelanguage<0.7.0,>=0.6.18->langchain-google-genai) (1.71.2)\n",
            "Requirement already satisfied: cachetools<6.0,>=2.0.0 in /usr/local/lib/python3.11/dist-packages (from google-auth!=2.24.0,!=2.25.0,<3.0.0,>=2.14.1->google-ai-generativelanguage<0.7.0,>=0.6.18->langchain-google-genai) (5.5.2)\n",
            "Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.11/dist-packages (from google-auth!=2.24.0,!=2.25.0,<3.0.0,>=2.14.1->google-ai-generativelanguage<0.7.0,>=0.6.18->langchain-google-genai) (0.4.2)\n",
            "Requirement already satisfied: rsa<5,>=3.1.4 in /usr/local/lib/python3.11/dist-packages (from google-auth!=2.24.0,!=2.25.0,<3.0.0,>=2.14.1->google-ai-generativelanguage<0.7.0,>=0.6.18->langchain-google-genai) (4.9.1)\n",
            "Requirement already satisfied: anyio in /usr/local/lib/python3.11/dist-packages (from httpx>=0.25.2->langgraph-sdk<0.2.0,>=0.1.42->langgraph) (4.9.0)\n",
            "Requirement already satisfied: httpcore==1.* in /usr/local/lib/python3.11/dist-packages (from httpx>=0.25.2->langgraph-sdk<0.2.0,>=0.1.42->langgraph) (1.0.9)\n",
            "Requirement already satisfied: h11>=0.16 in /usr/local/lib/python3.11/dist-packages (from httpcore==1.*->httpx>=0.25.2->langgraph-sdk<0.2.0,>=0.1.42->langgraph) (0.16.0)\n",
            "Requirement already satisfied: mypy-extensions>=0.3.0 in /usr/local/lib/python3.11/dist-packages (from typing-inspect<1,>=0.4.0->dataclasses-json<0.7,>=0.5.7->langchain-community) (1.1.0)\n",
            "Requirement already satisfied: pyasn1<0.7.0,>=0.6.1 in /usr/local/lib/python3.11/dist-packages (from pyasn1-modules>=0.2.1->google-auth!=2.24.0,!=2.25.0,<3.0.0,>=2.14.1->google-ai-generativelanguage<0.7.0,>=0.6.18->langchain-google-genai) (0.6.1)\n",
            "Requirement already satisfied: sniffio>=1.1 in /usr/local/lib/python3.11/dist-packages (from anyio->httpx>=0.25.2->langgraph-sdk<0.2.0,>=0.1.42->langgraph) (1.3.1)\n",
            "Enter your Google API Key: ··········\n",
            "🔍 Starting research on: Artificial Intelligence in Healthcare\n",
            "==================================================\n",
            "\n",
            "📍 Step 1: supervisor\n",
            "💬 Supervisor decision: Next agent is researcher...\n",
            "\n",
            "📍 Step 2: researcher\n",
            "💬 ## Research Topic: Artificial Intelligence in Healthcare\n",
            "\n",
            "This research explores the multifaceted applications of Artificial Intelligence (AI) within the healthcare sector, examining its benefits, cha...\n",
            "\n",
            "📍 Step 3: supervisor\n",
            "💬 Supervisor decision: Next agent is analyst...\n",
            "\n",
            "📍 Step 4: analyst\n",
            "💬 Analyzing Research Findings on Artificial Intelligence in Healthcare requires a nuanced approach, considering both the promising advancements and the significant challenges.  The following analysis ca...\n",
            "\n",
            "📍 Step 5: supervisor\n",
            "💬 Supervisor decision: Next agent is writer...\n",
            "\n",
            "📍 Step 6: writer\n",
            "💬 ## Artificial Intelligence in Healthcare: A Comprehensive Report\n",
            "\n",
            "**Executive Summary:**\n",
            "\n",
            "Artificial intelligence (AI) is rapidly transforming the healthcare landscape, offering the potential to revol...\n",
            "\n",
            "📍 Step 7: supervisor\n",
            "💬 Supervisor decision: Next agent is FINISH...\n",
            "\n",
            "==================================================\n",
            "📊 FINAL RESULTS\n",
            "==================================================\n",
            "🏁 Final Agent: supervisor\n",
            "📋 Findings: 2 sections\n",
            "📄 Report Length: 7240 characters\n",
            "\n",
            "📄 FINAL REPORT:\n",
            "------------------------------\n",
            "## Artificial Intelligence in Healthcare: A Comprehensive Report\n",
            "\n",
            "**Executive Summary:**\n",
            "\n",
            "Artificial intelligence (AI) is rapidly transforming the healthcare landscape, offering the potential to revolutionize diagnostics, treatment, and administrative processes.  This report examines the current state of AI in healthcare, exploring its key applications, benefits, challenges, and future implications.  While AI offers significant opportunities for improved accuracy, efficiency, and personalized care, critical challenges related to data privacy, algorithmic bias, and ethical considerations must be addressed to ensure responsible and equitable implementation.  This report highlights the need for robust regulatory frameworks, interoperable data systems, and a skilled workforce to fully harness the transformative potential of AI in healthcare.\n",
            "\n",
            "\n",
            "**I. Introduction:**\n",
            "\n",
            "The healthcare industry is facing increasing pressures to improve efficiency, reduce costs, and enhance the quality of care.  AI, with its ability to analyze vast amounts of data and identify patterns invisible to the human eye, offers a powerful tool to address these challenges.  This report explores the diverse applications of AI across various aspects of healthcare, from diagnostics and treatment to administrative functions and ethical considerations.\n",
            "\n",
            "\n",
            "**II. Key Applications of AI in Healthcare:**\n",
            "\n",
            "**A. Diagnostics:**\n",
            "\n",
            "* **Image Analysis:** AI algorithms are demonstrating remarkable success in analyzing medical images (X-rays, CT scans, MRIs, pathology slides), assisting clinicians in detecting diseases like cancer, cardiovascular conditions, and neurological disorders with increased accuracy and speed.  Deep learning models, in particular, have shown promising results in identifying subtle anomalies often missed by the human eye.  Examples include improved detection of diabetic retinopathy and early-stage lung cancer.\n",
            "\n",
            "* **Predictive Diagnostics:** AI can analyze patient data (genetics, lifestyle, medical history) to predict the likelihood of developing specific diseases.  This allows for proactive interventions, preventative measures, and personalized risk management strategies.  However, ethical considerations surrounding predictive modeling and potential biases require careful attention.\n",
            "\n",
            "* **Early Disease Detection:** AI's ability to identify subtle patterns in data allows for the detection of diseases at earlier stages, when treatment is often more effective.  This is particularly relevant for conditions like Alzheimer's disease and certain types of cancer.\n",
            "\n",
            "\n",
            "**B. Treatment & Therapy:**\n",
            "\n",
            "* **Personalized Medicine:** AI facilitates the development of personalized treatment plans based on individual patient characteristics and genetic information.  This approach moves beyond a \"one-size-fits-all\" model, optimizing treatment efficacy and minimizing adverse effects.  AI can analyze genomic data, patient history, and lifestyle factors to recommend the most appropriate treatment strategy.\n",
            "\n",
            "* **Robotic Surgery:** AI-assisted robotic surgery enhances precision, minimizes invasiveness, and improves surgical outcomes.  AI algorithms can guide surgical instruments, providing surgeons with real-time feedback and improving dexterity.\n",
            "\n",
            "* **Drug Discovery & Development:** AI accelerates the drug discovery process by identifying potential drug candidates, predicting drug efficacy, and optimizing clinical trials.  AI can analyze vast datasets of molecular structures and biological pathways to identify promising drug targets and predict their effectiveness.\n",
            "\n",
            "\n",
            "**C. Administrative & Operational Efficiency:**\n",
            "\n",
            "* **Workflow Streamlining:** AI automates administrative tasks such as appointment scheduling, billing, and claims processing, freeing up healthcare professionals to focus on patient care.  Chatbots and virtual assistants can handle routine inquiries, improving patient experience and reducing administrative burden.\n",
            "\n",
            "* **Predictive Analytics for Resource Allocation:** AI can predict patient demand and optimize resource allocation (staffing, beds, equipment), improving healthcare system efficiency and reducing costs.  This allows hospitals and clinics to better manage resources and avoid bottlenecks.\n",
            "\n",
            "* **Patient Monitoring & Remote Care:** AI-powered wearable sensors and remote monitoring systems enable continuous monitoring of patients' vital signs, facilitating early detection of complications and improving management of chronic conditions.  This reduces hospital readmissions and improves patient outcomes.\n",
            "\n",
            "\n",
            "**III. Challenges and Ethical Considerations:**\n",
            "\n",
            "* **Data Privacy and Security:**  The use of AI in healthcare necessitates the collection and analysis of vast amounts of sensitive patient data.  Robust data privacy and security measures are crucial to comply with regulations like HIPAA and GDPR and maintain patient trust.\n",
            "\n",
            "* **Algorithmic Bias and Fairness:** AI algorithms trained on biased data can perpetuate and amplify existing health disparities.  Ensuring fairness and equity in AI-driven healthcare requires careful attention to data representation and algorithm design.\n",
            "\n",
            "* **Liability and Accountability:**  Determining responsibility in cases of AI-related medical errors or misdiagnosis requires clear legal frameworks and guidelines.\n",
            "\n",
            "* **Job Displacement and Workforce Adaptation:**  The automation of certain tasks through AI may lead to job displacement in the healthcare sector.  Proactive strategies for workforce retraining and upskilling are essential to mitigate this risk.\n",
            "\n",
            "\n",
            "**IV. Future Implications:**\n",
            "\n",
            "The future of AI in healthcare is bright, with ongoing research and development promising further advancements in diagnostics, treatment, and administrative efficiency.  We can expect to see:\n",
            "\n",
            "* Increased integration of AI into clinical workflows.\n",
            "* More sophisticated AI algorithms capable of handling complex medical tasks.\n",
            "* Wider adoption of personalized medicine and remote patient monitoring.\n",
            "* Development of new AI-driven therapies and treatments.\n",
            "\n",
            "\n",
            "**V. Conclusion and Recommendations:**\n",
            "\n",
            "AI has the potential to transform healthcare, improving patient outcomes, enhancing efficiency, and reducing costs.  However, realizing this potential requires addressing the challenges related to data privacy, algorithmic bias, and ethical considerations.  Key recommendations include:\n",
            "\n",
            "* **Developing robust regulatory frameworks:**  Clear guidelines and regulations are needed to ensure responsible and ethical use of AI in healthcare.\n",
            "* **Investing in data infrastructure:**  High-quality, standardized, and interoperable data systems are essential for developing and deploying effective AI algorithms.\n",
            "* **Promoting collaboration and transparency:**  Collaboration between researchers, clinicians, policymakers, and technology developers is crucial for successful AI implementation.\n",
            "* **Addressing workforce adaptation:**  Investing in training and education to equip healthcare professionals with the skills needed to effectively utilize and manage AI systems is essential.\n",
            "\n",
            "\n",
            "By addressing these challenges and fostering collaboration, we can harness the transformative power of AI to create a more efficient, equitable, and effective healthcare system for all.\n",
            "🚀 LangGraph Research Team - Quick Start Demo\n",
            "==================================================\n",
            "\n",
            "🔍 Demo 1: Climate Change Impact on Agriculture\n",
            "----------------------------------------\n",
            "🔍 Starting research on: Climate Change Impact on Agriculture\n",
            "==================================================\n",
            "\n",
            "📍 Step 1: supervisor\n",
            "💬 Supervisor decision: Next agent is researcher...\n",
            "\n",
            "📍 Step 2: researcher\n",
            "💬 ## Research Topic: Climate Change Impact on Agriculture\n",
            "\n",
            "This research topic is vast and encompasses numerous interconnected areas.  To effectively analyze it, we need to break it down into key areas ...\n",
            "\n",
            "📍 Step 3: supervisor\n",
            "💬 Supervisor decision: Next agent is analyst...\n",
            "\n",
            "📍 Step 4: analyst\n",
            "💬 Analyzing research findings on climate change's impact on agriculture requires synthesizing information from numerous studies across various disciplines.  There's no single, universally agreed-upon co...\n",
            "\n",
            "📍 Step 5: supervisor\n",
            "💬 Supervisor decision: Next agent is writer...\n",
            "\n",
            "📍 Step 6: writer\n",
            "💬 ## The Impact of Climate Change on Agriculture: A Comprehensive Report\n",
            "\n",
            "**Executive Summary:**\n",
            "\n",
            "Climate change poses a significant and multifaceted threat to global agriculture.  Rising temperatures, ...\n",
            "\n",
            "📍 Step 7: supervisor\n",
            "💬 Supervisor decision: Next agent is FINISH...\n",
            "✅ Research completed successfully!\n",
            "📊 Report preview: ## The Impact of Climate Change on Agriculture: A Comprehensive Report\n",
            "\n",
            "**Executive Summary:**\n",
            "\n",
            "Climate change poses a significant and multifaceted th...\n",
            "\n",
            "==============================\n",
            "\n",
            "🔍 Demo 2: Quantum Computing Applications\n",
            "----------------------------------------\n",
            "🔍 Starting research on: Quantum Computing Applications\n",
            "==================================================\n",
            "\n",
            "📍 Step 1: supervisor\n",
            "💬 Supervisor decision: Next agent is researcher...\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "WARNING:langchain_google_genai.chat_models:Retrying langchain_google_genai.chat_models._chat_with_retry.<locals>._chat_with_retry in 2.0 seconds as it raised ResourceExhausted: 429 You exceeded your current quota, please check your plan and billing details. For more information on this error, head to: https://ai.google.dev/gemini-api/docs/rate-limits. [violations {\n",
            "  quota_metric: \"generativelanguage.googleapis.com/generate_content_free_tier_requests\"\n",
            "  quota_id: \"GenerateRequestsPerMinutePerProjectPerModel-FreeTier\"\n",
            "  quota_dimensions {\n",
            "    key: \"model\"\n",
            "    value: \"gemini-1.5-flash\"\n",
            "  }\n",
            "  quota_dimensions {\n",
            "    key: \"location\"\n",
            "    value: \"global\"\n",
            "  }\n",
            "  quota_value: 15\n",
            "}\n",
            ", links {\n",
            "  description: \"Learn more about Gemini API quotas\"\n",
            "  url: \"https://ai.google.dev/gemini-api/docs/rate-limits\"\n",
            "}\n",
            ", retry_delay {\n",
            "  seconds: 14\n",
            "}\n",
            "].\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "📍 Step 2: researcher\n",
            "💬 ## Research Topic: Quantum Computing Applications\n",
            "\n",
            "This research explores the potential applications of quantum computing across various fields.  While still in its nascent stages, quantum computing h...\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "WARNING:langchain_google_genai.chat_models:Retrying langchain_google_genai.chat_models._chat_with_retry.<locals>._chat_with_retry in 2.0 seconds as it raised ResourceExhausted: 429 You exceeded your current quota, please check your plan and billing details. For more information on this error, head to: https://ai.google.dev/gemini-api/docs/rate-limits. [violations {\n",
            "  quota_metric: \"generativelanguage.googleapis.com/generate_content_free_tier_requests\"\n",
            "  quota_id: \"GenerateRequestsPerMinutePerProjectPerModel-FreeTier\"\n",
            "  quota_dimensions {\n",
            "    key: \"model\"\n",
            "    value: \"gemini-1.5-flash\"\n",
            "  }\n",
            "  quota_dimensions {\n",
            "    key: \"location\"\n",
            "    value: \"global\"\n",
            "  }\n",
            "  quota_value: 15\n",
            "}\n",
            ", links {\n",
            "  description: \"Learn more about Gemini API quotas\"\n",
            "  url: \"https://ai.google.dev/gemini-api/docs/rate-limits\"\n",
            "}\n",
            ", retry_delay {\n",
            "  seconds: 12\n",
            "}\n",
            "].\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n",
            "📍 Step 3: supervisor\n",
            "💬 Supervisor error: 429 You exceeded your current quota, please check your plan and billing details. For more information on this error, head to: https://ai.google.dev/gemini-api/docs/rate-limits. [viol...\n",
            "❌ Research failed\n",
            "\n",
            "==============================\n",
            "\n",
            "🔍 Demo 3: Digital Privacy in the Modern Age\n",
            "----------------------------------------\n",
            "🔍 Starting research on: Digital Privacy in the Modern Age\n",
            "==================================================\n",
            "\n",
            "📍 Step 1: supervisor\n",
            "💬 Supervisor decision: Next agent is researcher...\n",
            "\n",
            "📍 Step 2: researcher\n",
            "💬 ## Research Topic: Digital Privacy in the Modern Age\n",
            "\n",
            "This research topic is vast and multifaceted.  To effectively analyze it, we need to break it down into key areas.\n",
            "\n",
            "**I. Key Areas Requiring Inves...\n",
            "\n",
            "📍 Step 3: supervisor\n",
            "💬 Supervisor decision: Next agent is analyst...\n",
            "\n",
            "📍 Step 4: analyst\n",
            "💬 Analyzing research findings on digital privacy in the modern age requires synthesizing information from various sources, including legal scholarship, technological analyses, sociological studies, and ...\n",
            "\n",
            "📍 Step 5: supervisor\n",
            "💬 Supervisor decision: Next agent is writer...\n",
            "\n",
            "📍 Step 6: writer\n",
            "💬 ## Digital Privacy in the Modern Age: A Comprehensive Report\n",
            "\n",
            "**Executive Summary:**\n",
            "\n",
            "The digital age has ushered in unprecedented advancements, but it has also created a complex landscape of digital ...\n",
            "\n",
            "📍 Step 7: supervisor\n",
            "💬 Supervisor decision: Next agent is FINISH...\n",
            "✅ Research completed successfully!\n",
            "📊 Report preview: ## Digital Privacy in the Modern Age: A Comprehensive Report\n",
            "\n",
            "**Executive Summary:**\n",
            "\n",
            "The digital age has ushered in unprecedented advancements, but i...\n",
            "\n",
            "==============================\n",
            "🎉 Demo completed!\n"
          ]
        }
      ]
    }
  ]
}